package fr.Orm.pierop.com;

import java.util.Map;

import fr.dbManager.pierop.com.DBManager;
import fr.myExceptions.pierop.com.beanEmptyException;
import fr.xmlParser.pierop.com.IReadConfFile;
import fr.xmlParser.pierop.com.readConfFile;

public class ORM implements IORM {

	private Integer					verbose = new Integer("0");
	private Introspection			introsClass;
	private readConfFile			xmlFile;
	private DBManager				db;
	private facadeJDBC				facade;
	
	public ORM() throws Exception {
		
		this.xmlFile = new readConfFile();
		this.xmlFile.readProperty();
		this.xmlFile.readBean();
		this.setModeVerbose();
		if (this.isModeVerbose()) { this.xmlFile.printBean(); this.xmlFile.printProperty(); }
		this.db = DBManager.getInstance(this.xmlFile.getProperty().get(IReadConfFile.driverDB),
										this.xmlFile.getProperty().get(IReadConfFile.pathDB),
										this.xmlFile.getProperty().get(IReadConfFile.userDB),
										this.xmlFile.getProperty().get(IReadConfFile.passDB));
		this.db.connection(this.isModeVerbose());
		this.introsClass = Introspection.getInstance();
		this.facade = facadeJDBC.getInstance(this.introsClass.getTableMap(), this.introsClass.getClassMap());
		this.createTablesForBeans();
	}
	
	private void	setModeVerbose() 	{ 
		if (this.xmlFile.getProperty().get(IReadConfFile.verboseMode) != null &&
			this.xmlFile.getProperty().get(IReadConfFile.verboseMode).equals("1"))
			this.verbose = new Integer("1");
		}
	private boolean isModeVerbose() { if (this.verbose.equals(1)) return true; else return false; }
	
	private void createTablesForBeans() throws Exception
	{
		if (this.xmlFile.getBean().isEmpty()) { throw new beanEmptyException(); }
		if (this.isModeVerbose()) { System.out.println(IORM.createDBText); }
		for (Map.Entry<String, String> e : this.xmlFile.getBean().entrySet()) {
			this.introsClass.createDatabase(e.getKey(), e.getValue(), this.isModeVerbose());
		}
	}

	@Override
	public void save(Object obj) throws Exception {
		this.facade.create(obj);
	}

	@Override
	public void update(Object obj) throws Exception {
		this.facade.update(obj);
	}

	@Override
	public void delete(Object obj) throws Exception {
		this.facade.delete(obj);
	}

	@Override
	public Object get(Class clas, Integer id) throws Exception {
		return this.facade.select(clas, id);
	}
}
